/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

/**
 *
 * http配置
 *
 */

import axios from 'axios'
import store from '../store'
import router from '../router/router'
import { getToken, setToken, removeToken } from '@/util/auth'
import { Message } from 'element-ui'
import errorCode from '@/const/errorCode'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import { baseUrl } from '@/config/env'
import qs from 'qs'

// progress bar style
// 超时时间
axios.defaults.timeout = 30000
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true

if (process.env.NODE_ENV == 'development') {
  //本地api请求路径
  console.log('本地axios base url' + baseUrl)
  axios.defaults.baseURL = baseUrl
} else if (process.env.NODE_ENV == 'production') {
  //线上api请求路径
  console.log('线上axios base url' + baseUrl)
  axios.defaults.baseURL = baseUrl
}

NProgress.configure({ showSpinner: false })// NProgress Configuration
let msg
// HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // start progress bar
  if (store.getters.access_token) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }

  if (config.method === 'get') {
    config.paramsSerializer = function(params) {
      return qs.stringify(params, { arrayFormat: 'brackets' })
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})
// HTTPresponse拦截
axios.interceptors.response.use(data => {
  NProgress.done()
  return data
}, error => {
  NProgress.done()
  let errMsg = error.toString()
  let code = errMsg.substr(errMsg.indexOf('code') + 5)
  Message({
    message: errorCode[code] || errorCode['default'],
    type: 'error'
  })
  return Promise.reject(new Error(error))
})

axios.interceptors.response.use(function(response) {
  // Do something with response data
  if (response.data.type != undefined && response.data.type == 'application/vnd.ms-excel') {
    console.log('response.data', response.data.type)
    const exportLink = document.createElement('a')
    let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    exportLink.style.display = 'none'
    //设置连接
    exportLink.href = URL.createObjectURL(blob)
    exportLink.download = (new Date()).valueOf() + '.xlsx'
    document.body.appendChild(exportLink)
    //模拟点击事件
    exportLink.click()
  }
  return response
}, function(error) {
  // Do something with response error
  return Promise.reject(error)
})

export default axios
